package ru.beta2.testyard;

import junit.framework.TestCase;
import ru.beta2.testyard.config.Configuration;

/**
 * Base class for test cases.
 * <br/>
 * User: Inc
 * Date: 18.01.2009
 * Time: 14:56:07
 */
public abstract class TestyardCase extends TestCase
{
    /**
     * Testyard framework entry point.
     */
    protected TestYard yard;
    /**
     * Current scenario ({@link TestYard#getScenario()})
     */
    protected Scenario scenario;
    /**
     * Current step.
     * Methods {@link #next()} and {@link #next(String)} ensure keep this reference to current step object.
     */
    private Step step;
    /**
     * Current script.
     * Methods {@link #next()} and {@link #next(String)} ensure keep this reference to current script object.
     */
    protected Script script;
    /**
     * Shortcut for {@link Scenario#getMessageControl()}
     */
    protected MessageControl mctl;
    /**
     * Used testyard configuration
     */
    protected Configuration cfg;

    /**
     * Setup testyard infrastructure and basic fixture.
     * Creates testyard configuration with calling {@link #getConfiguration()}, creates {@link TestYard) object,
     * clears server state ({@link ru.beta2.testyard.TestYard#clearDatabase()}), assigns fields
     * @throws Exception
     */
    protected void setUp() throws Exception
    {
        super.setUp();
        cfg = getConfiguration(); 
        yard = new TestYard(cfg);
        yard.clearDatabase();

        scenario = yard.getScenario();
        step = scenario;
        script = scenario;
        mctl = scenario.getMessageControl();
    }

    /**
     * Override this method for tune testyard configuration
     * @return configuration for testyard
     */
    protected Configuration getConfiguration()
    {
        return new Configuration();
    }

    /**
     * Teardown testyard infrastructure
     * @throws Exception
     */
    protected void tearDown() throws Exception
    {
        yard.close();
        super.tearDown();
    }

    /**
     * Run scenario shortcut.   
     */
    protected void go()
    {
        scenario.go();
    }

    /**
     * Begin new scenario step with default name (default step names: 2nd, 3rd, 4th and so on)
     */
    protected void next()
    {
        next(null);
    }

    /**
     * Begin new step in scenario
     * @param stepName name (label) of the step
     */
    protected void next(String stepName)
    {
        if (stepName == null) {
            step = step.nextStep();
        }
        else {
            step = step.nextStep(stepName);
        }
        script = step;
    }

    /**
     * Shortcut for obtain player's name
     * @param no - number of player
     * @return no'th player's name
     */
    protected String player(int no)
    {
        return cfg.getPlayersHandler().getPlayerName(no);
    }
}
